
local ADDON, ns = ...
local LSM = LibStub and LibStub("LibSharedMedia-3.0", true)
local AceConfig = LibStub and LibStub("AceConfig-3.0", true)
local AceConfigDialog = LibStub and LibStub("AceConfigDialog-3.0", true)
local AceDB = LibStub and LibStub("AceDB-3.0", true)
local AceDBOptions = LibStub and LibStub("AceDBOptions-3.0", true)

local function DB() return (ns.db and ns.db.profile) or _G.InterruptHelperDB end

local function registerCustomSound(path)
    if not (LSM and path and path ~= "") then return end
    local name = path:match("([^\\/:]+)$") or "Custom"
    LSM:Register("sound", name, path)
end

local function commaListToTable(text)
    local t = {}
    for s in string.gmatch(text or "", "[^,%s]+") do
        local id = tonumber(s)
        if id then t[id] = true end
    end
    return t
end

local function tableToCommaList(tab)
    local tmp = {}
    for id,_ in pairs(tab or {}) do table.insert(tmp, tostring(id)) end
    table.sort(tmp, function(a,b) return tonumber(a)<tonumber(b) end)
    return table.concat(tmp, ", ")
end

local function buildAceOptions()
    if not AceConfig or not AceConfigDialog then return end

    local options = {
        type = "group",
        name = "打断助手 - \124cff00ffffv1.9.3b\124r 汉化版 by \124cffff00ffM.O.S.S\124r",
        args = {
            general = {
                type = "group",
                name = "基础设置",
                order = 1,
                args = {
                    enabled = { type="toggle", name="启用插件", order=1,
                        get=function() return DB().enabled end,
                        set=function(_,v) DB().enabled=v end },

                    language = { type="select", name="语言", order=1.1,
                        values = { AUTO="自动", zhCN="中文", enUS="英语" },
                        get=function() return DB().language end,
                        set=function(_,v) DB().language=v end },
                    output = { type="select", name="警告声道", order=2,
                        values={ Master="主音量", SFX="效果", Dialog="对话", Music="音乐", Ambience="环境音" },
                        get=function() return DB().volume end,
                        set=function(_,v) DB().volume=v end },
                    useVol = { type="toggle", name="自定义警告音量", order=3,
                        get=function() return DB().useVolumeSlider end,
                        set=function(_,v) DB().useVolumeSlider=v end,
                        desc="通过临时调整频道音量来模拟每个警报的独立音量效果。" },
                    vol = { type="range", name="警告音量", order=4,
                        min=0, max=1, step=0.01, isPercent=true,
                        disabled=function() return not DB().useVolumeSlider end,
                        get=function() return DB().volumeSlider end,
                        set=function(_,v) DB().volumeSlider=v end },
                    soundSel = { type="select", name="警告音", order=10,
                        values=function()
                            local t={ RAID_WARNING="团队警报（音效系统）", ALARM="闹钟（音效系统）", CUSTOM="自定义文件（路径见下方）" }
                            if LSM then t["__sep"]="— LibSharedMedia —"; for _,key in ipairs(LSM:List("sound")) do t["LSM:"..key]="LSM: "..key end end
                            return t
                        end,
                        sorting=function()
                            local order={"RAID_WARNING","ALARM","CUSTOM","__sep"}
                            if LSM then for _,key in ipairs(LSM:List("sound")) do table.insert(order,"LSM:"..key) end end
                            return order
                        end,
                        get=function() return DB().sound end,
                        set=function(_,v) DB().sound=v end },
                    customPath = { type="input", name="自定义文件路径(OGG/MP3)", order=11, width="full",
                        get=function() return DB().customPath end,
                        set=function(_,v) DB().customPath=v; registerCustomSound(v) end },
                    test = { type="execute", name="播放测试", order=12,
                        func=function() SlashCmdList["INTERRUPTHELPER"]("test") end },
                },
            },
            filter = {
                type = "group",
                name = "过滤设置",
                order = 1.5,
                args = {
                    mode = { type="select", name="通知", order=1,
                        values={ ALL="所有可打断的法术", IMPORTANT="仅重要法术（列表与预设）" },
                        get=function() return DB().filterMode end,
                        set=function(_,v) DB().filterMode=v end },
                    scope = { type="select", name="区域", order=2,
                        values={ ANY="全部", INSTANCES="仅地下城/团本", RAID="仅团本" },
                        get=function() return DB().instanceScope end,
                        set=function(_,v) DB().instanceScope=v end },
                    dungeonDiffHeader = { type="header", name="地下城难度等级", order=2.1 },
                    dN = { type="toggle", name="普通", order=2.2,
                        get=function() return (DB().dungeonDiff or {}).N end,
                        set=function(_,v) DB().dungeonDiff.N=v end },
                    dH = { type="toggle", name="英雄", order=2.3,
                        get=function() return (DB().dungeonDiff or {}).H end,
                        set=function(_,v) DB().dungeonDiff.H=v end },
                    dM = { type="toggle", name="史诗", order=2.4,
                        get=function() return (DB().dungeonDiff or {}).M end,
                        set=function(_,v) DB().dungeonDiff.M=v end },
                    dMP = { type="toggle", name="大秘境", order=2.5,
                        get=function() return (DB().dungeonDiff or {}).MPLUS end,
                        set=function(_,v) DB().dungeonDiff.MPLUS=v end },
                    raidDiffHeader = { type="header", name="团本难度等级", order=2.6 },
                    rLFR = { type="toggle", name="随机", order=2.7,
                        get=function() return (DB().raidDiff or {}).LFR end,
                        set=function(_,v) DB().raidDiff.LFR=v end },
                    rN = { type="toggle", name="普通", order=2.8,
                        get=function() return (DB().raidDiff or {}).N end,
                        set=function(_,v) DB().raidDiff.N=v end },
                    rH = { type="toggle", name="英雄", order=2.9,
                        get=function() return (DB().raidDiff or {}).H end,
                        set=function(_,v) DB().raidDiff.H=v end },
                    rM = { type="toggle", name="史诗", order=3.0,
                        get=function() return (DB().raidDiff or {}).M end,
                        set=function(_,v) DB().raidDiff.M=v end },

                    usePresetDungeon = { type="toggle", name="剧情模式：地下城（正式服）", order=3.2,
                        get=function() return DB().usePresetDungeon end,
                        set=function(_,v) DB().usePresetDungeon=v end },
                    usePresetRaid = { type="toggle", name="剧情模式：团本（正式服）", order=3.3,
                        get=function() return DB().usePresetRaid end,
                        set=function(_,v) DB().usePresetRaid=v end },

                    list = { type="input", name="自定义重要法术（法术ID，用英文格式逗号分隔）", order=4, width="full", multiline=true,
                        get=function() return tableToCommaList(DB().importantSpells) end,
                        set=function(_,v) DB().importantSpells = commaListToTable(v) end },
                    hint = { type="description", name="命令提示： /ih add <id>, /ih remove <id>, /ih list", order=5 },
                    blacklistHeader = { type="header", name="禁止通报的法术ID", order=5.5 },
                    blacklist = { type="input", name="自定义黑名单（法术ID，用英文格式逗号分隔）", order=5.6, width="full", multiline=true,
                        get=function() return tableToCommaList(DB().ignoreSpells) end,
                        set=function(_,v) DB().ignoreSpells = commaListToTable(v) end },
						
                },
            },
            announce = {
                type = "group",
                name = "聊天通报",
                order = 1.8,
                args = {
                    enabled = { type="toggle", name="启用聊天通知播报", order=1,
                        get=function() return DB().announceEnabled end,
                        set=function(_,v) DB().announceEnabled=v end },
                    channel = { type="select", name="频道", order=2,
                        hidden=function() return not DB().announceEnabled end,
                        values = { AUTO="自动（地下城/团队/小队/说)", PARTY="小队", RAID="团队", INSTANCE_CHAT="地下城", SAY="说" },
                        get=function() return DB().announceChannel end,
                        set=function(_,v) DB().announceChannel=v end },
                    template = { type="input", name="通报模板", order=3, width="full",
                        hidden=function() return not DB().announceEnabled end,
                        desc="施法者: %spell% = 技能, %mob% = 敌人",
                        get=function() return DB().announceTemplate end,
                        set=function(_,v) DB().announceTemplate=v end },
                    throttle = { type="range", name="通报频率", order=4, min=0, max=10, step=0.5,
                        hidden=function() return not DB().announceEnabled end,
                        get=function() return DB().announceThrottleS end,
                        set=function(_,v) DB().announceThrottleS=v end },
                    inWorld = { type="toggle", name="副本外允许通报", order=5,
                        hidden=function() return not DB().announceEnabled end,
                        get=function() return DB().announceInWorld end,
                        set=function(_,v) DB().announceInWorld=v end },
                    onlyReady = { type="toggle", name="仅当我的打断技能就绪时通报", order=6,
                        hidden=function() return not DB().announceEnabled end,
                        get=function() return DB().announceOnlyIfReady end,
                        set=function(_,v) DB().announceOnlyIfReady=v end },
                    preview = { type="execute", name="通报测试(说)", order=7,
                        hidden=function() return not DB().announceEnabled end,
                        func=function()
                            local t = (DB().announceTemplate or "注意：%mob%正在施放%spell% - 请立即打断！")
                            t = t:gsub("%%spell%%","[技能名称]"):gsub("%%mob%%","[敌人名称]")
                            SendChatMessage(t, "SAY")
                        end },
                    debugAnn = { type="toggle", name="通报调试", order=99,
                        hidden=function() return not DB().announceEnabled end,
                        get=function() return DB().debugAnnounce end,
                        set=function(_,v) DB().debugAnnounce=v end },
                },
            },			
            text = {
                type = "group",
                name = "屏幕提示",
                order = 2,
                args = {
                    show = { type="toggle", name="显示文字警告", order=1,
                        get=function() return DB().showText end,
                        set=function(_,v) DB().showText=v; if v and ns and ns.ShowPreview then ns.ShowPreview() else if ns and ns.HidePreview then ns.HidePreview() end end end },
                    sticky = { type="toggle", name="测试界面持续显示", order=2,
                        get=function() return DB().testSticky end,
                        set=function(_,v) DB().testSticky=v; if v and ns and ns.ShowPreview then ns.ShowPreview() end end },
                    duration = { type="range", name="显示时长（秒）", order=3, min=1, max=3, step=0.1,
                        get=function() return DB().textDuration end,
                        set=function(_,v) DB().textDuration=v end },
                    content = { type="input", name="文字", order=4, width="full",
                        get=function() return DB().text end,
                        set=function(_,v) DB().text=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    font = { type="select", name="字体", order=5,
                        values=function() local t={ [""]="标准" } if LSM then for _,key in ipairs(LSM:List("font")) do t[key]=key end end return t end,
                        get=function() return DB().textFont or "" end,
                        set=function(_,v) DB().textFont=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    size = { type="range", name="字体大小", order=6, min=12, max=96, step=1,
                        get=function() return DB().textSize end,
                        set=function(_,v) DB().textSize=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    outline = { type="select", name="轮廓", order=7,
                        values={ NONE="无", OUTLINE="细", THICKOUTLINE="粗", MONOCHROME="单色", MONOCHROMEOUTLINE="单色描边" },
                        get=function() return DB().textOutline end,
                        set=function(_,v) DB().textOutline=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    color = { type="color", name="字体颜色", order=8, hasAlpha=false,
                        get=function() local c=DB().textColor; return c.r,c.g,c.b,1 end,
                        set=function(_,r,g,b) DB().textColor={r=r,g=g,b=b,a=DB().textAlpha or 1}; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    textAlpha = { type="range", name="字体透明度", order=9, min=0, max=1, step=0.01, isPercent=true,
                        get=function() return DB().textAlpha end,
                        set=function(_,v) DB().textAlpha=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    bgAlpha = { type="range", name="背景透明度", order=10, min=0, max=1, step=0.01, isPercent=true,
                        get=function() return DB().bgAlpha end,
                        set=function(_,v) DB().bgAlpha=v; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                    place = { type="execute", name="定位（解锁）", order=11,
                        func=function() SlashCmdList["INTERRUPTHELPER"]("unlock") end },
                    hide = { type="execute", name="隐藏测试条", order=12,
                        func=function() if ns and ns.HidePreview then ns.HidePreview() end end },
                    lock = { type="execute", name="锁定", order=13,
                        func=function() SlashCmdList["INTERRUPTHELPER"]("lock") end },
                    apply = { type="execute", name="应用样式+测试", order=14,
                        func=function() if ns and ns.applyTextStyle then ns.applyTextStyle() end; if ns and ns.ShowPreview then ns.ShowPreview() end end },
                },
            },
        },
    }

    -- Register parent FIRST
    AceConfig:RegisterOptionsTable("InterruptHelper", options)
    AceConfigDialog:AddToBlizOptions("InterruptHelper", "InterruptHelper")

    -- Profiles sub-category (if AceDB present)
    if AceDB and AceDBOptions and ns.db then
        local profiles = AceDBOptions:GetOptionsTable(ns.db)
        AceConfig:RegisterOptionsTable("InterruptHelper-Profiles", profiles)
        AceConfigDialog:AddToBlizOptions("InterruptHelper-Profiles", "Profiles", "InterruptHelper")
    end
end

local function buildBasicPanel()
    if AceConfig and AceConfigDialog then return end
    local f = CreateFrame("Frame", "InterruptHelperOptionsPanel")
    f.name = "InterruptHelper"

    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 16, -16)
    title:SetText("打断助手 – 基础设置")

    local cb = CreateFrame("CheckButton", nil, f, "InterfaceOptionsCheckButtonTemplate")
    cb:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -12)
    cb.Text:SetText("激活插件")
    cb:SetChecked(DB().enabled)
    cb:SetScript("OnClick", function(self) DB().enabled = self:GetChecked() end)

    local hint = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    hint:SetPoint("TOPLEFT", cb, "BOTTOMLEFT", 0, -10)
    hint:SetText("提示：安装Ace3库和LibSharedMedia库以启用高级选项。")

    if Settings and Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory then
        local category = Settings.RegisterCanvasLayoutCategory(f, "InterruptHelper")
        category.ID = "InterruptHelper"
        Settings.RegisterAddOnCategory(category)
        ns.categoryID = category.ID
    elseif InterfaceOptions_AddCategory then
        InterfaceOptions_AddCategory(f)
        ns.categoryID = "InterruptHelper"
    end
end

local e = CreateFrame("Frame")
e:RegisterEvent("PLAYER_LOGIN")
e:SetScript("OnEvent", function()
    if type(InterruptHelperDB) ~= "table" then _G.InterruptHelperDB = {} end
    buildAceOptions()
    buildBasicPanel()
end)

function ns.OpenOptions()
    if AceConfigDialog then
        AceConfigDialog:Open("InterruptHelper")
    elseif Settings and Settings.OpenToCategory and ns.categoryID then
        Settings.OpenToCategory(ns.categoryID)
    elseif InterfaceOptionsFrame_OpenToCategory and ns.categoryID then
        InterfaceOptionsFrame_OpenToCategory(ns.categoryID)
        InterfaceOptionsFrame_OpenToCategory(ns.categoryID)
    end
end
